package entity

import (
	"errors"
	"fmt"
	"time"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/workflow"
	"shqsoft.cn/pas3ui/workflow/entity"

	"gorm.io/gorm"
)

//SpGhbg 工号变更
type SpGhbg struct {
	ID         int       `gorm:"column:ID;AUTO_INCREMENT;primary_key" json:"id"`
	SQR        int       `gorm:"column:SQR" json:"sqr"`
	SQSJ       time.Time `gorm:"column:SQSJ" json:"sqsj"`
	SYSUSERIDY string    `gorm:"column:SysUserIDy" json:"sysuseridy"`
	SYSUSERIDX string    `gorm:"column:SysUserIDx" json:"sysuseridx"`
	UserName   string    `gorm:"column:UserName" json:"userName"`
	OrganName  string    `gorm:"column:OrganName" json:"organName"`
	WFID       int       `gorm:"column:WFID" json:"wfid"`
	FRID       int       `gorm:"column:FRID" json:"frid"`
	Progress   float32   `gorm:"-" json:"progress"`
	StepName   string    `gorm:"-" json:"stepName"`
	Status     string    `gorm:"-" json:"status"`
	STEP       int       `gorm:"-" json:"step"`
}

//TableName SpGhbg表名
func (SpGhbg) TableName() string {
	return "T_SP_GHBG"
}

//BeforeSave 保存前的触发器
func (s *SpGhbg) BeforeSave(tx *gorm.DB) (err error) {
	var count int
	row := tx.Raw("select count(id) from T_SysUser where SysUserID=?", s.SYSUSERIDY).Row()
	row.Scan(&count)
	if count == 0 {
		return fmt.Errorf("原工号:%s不存在！", s.SYSUSERIDY)
	}
	row = tx.Raw("select count(id) from T_SysUser where SysUserID=?", s.SYSUSERIDX).Row()
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("新工号:%s已存在，请修改！", s.SYSUSERIDX)
	}
	var frids []int
	tx.Table("T_SP_GHBG").Where("SysUserIDy=?", s.SYSUSERIDY).Pluck("FRID", &frids)
	row = tx.Raw("select count(id) from T_FLOW_RUN where ID in (?) and STATE in (0,1)", frids).Row()
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("原工号:%s已经申请过了，请不要重复申请！", s.SYSUSERIDY)
	}
	var frids2 []int
	tx.Table("T_SP_GHBG").Where("SysUserIDx=?", s.SYSUSERIDX).Pluck("FRID", &frids2)
	row = tx.Raw("select count(id) from T_FLOW_RUN where ID in (?) and STATE in (0,1)", frids2).Row()
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("新工号:%s已经申请过了，请不要重复申请！", s.SYSUSERIDX)
	}
	tx.Raw("select EMNM,DPNM from DIM_USER where emid=?", s.SQR).Row().Scan(&s.UserName, &s.OrganName)
	if s.FRID == 0 {
		ei, _ := workflow.GetEntityInfo("SpGhbg")
		s.WFID, err = ei.WfidFunc(s)
		if err != nil {
			return err
		}
		if s.WFID == 0 {
			return errors.New("获取用户申请WFID失败")
		}
		runid, err := workflow.Create(s.WFID, s.SQR, tx)
		if err != nil {
			return err
		}
		s.FRID = runid
	}
	return
}

func (s *SpGhbg) AfterDelete(tx *gorm.DB) (err error) {
	if s.FRID > 0 {
		return workflow.Delete(s.FRID)
	}
	return nil
}

// AfterFind 查询后触发器
func (s *SpGhbg) AfterFind(tx *gorm.DB) (err error) {
	if s.FRID == 0 {
		s.Status = "exception"
		s.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, s.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	s.STEP = run.Step
	s.StepName = act.Desc
	s.Progress = float32(act.Step*100) / float32(count)
	if s.Progress >= 100 && run.State == "0" {
		s.Progress = 95
	}
	s.Status = ""
	if run.State == "0" {
		s.Status = "active"
	} else if run.State == "2" {
		s.Status = "exception"
	} else {
		s.Status = "success"
	}
	return
}

//SpGhbgEF 获取实体类对象
func SpGhbgEF() base.EntityFunc {
	return func() interface{} {
		entity := SpGhbg{}
		return &entity
	}
}

//SpGhbgESF 获取实体类对象数组
func SpGhbgESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SpGhbg
		return &entities
	}
}
func init() {
	dao := base.NewDefaultDao(SpGhbgEF(), SpGhbgESF(), nil, "my")
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetDB("my")
	ei, err := workflow.GetEntityInfo("SpGhbg")
	if err != nil {
		panic(err)
	}
	filter.SetAdditional("wfid", ei.WfidsToString())
	filter.SetAdditional("manager", ei.MgMapToString())
	dao.Fileter = &filter
	base.DaoPoolObj.Put("SpGhbg", dao)
}
